const Router = require('koa-router')
const formatDate = require('../../utils/dateFormat').formatDate
const passport = require('koa-passport')
const router = new Router()
const mongoose = require('mongoose')

const Repository = require('../../models/Repository')
const Blood = require('../../models/Blood')
const Volunteer = require('../../models/Volunteer')

/**
 * @description test 仓库数量
 */
router.get('/report', async ctx => {
  let findResult = await Blood.aggregate([
    { $group: { "_id": "$reposName", count: { $sum: 1 } } }
  ])
  const keyMap = {
    '_id': 'name',
    'count': 'value'
  }
  for (let i in findResult) {
    const obj = findResult[i]
    for (let key in obj) {
      let newKey = keyMap[key]
      if (newKey) {
        obj[newKey] = obj[key]
        delete obj[key]
      }
    }
  }
  for (let i in findResult) {
    if (!findResult[i].name) {
      findResult.splice(i, 1)
    }
  }
  ctx.status = 200
  ctx.body = findResult
})
/**
 * @description 查询仓库分页
 */
router.get('/page', async ctx => {
  const query = ctx.request.query
  let page = Number(query.page) ? Number(query.page) : 1
  let size = Number(query.per_page) ? Number(query.per_page) : 9999
  // let IDNo = query.IDNo ? new RegExp(query.IDNo) : /[\s\S]*/
  let name = query.name ? new RegExp(query.name) : /[\s\S]*/
  let skip = (page - 1) * size
  let findResult = await Repository.find({ $or: [{ name: { $regex: name } }], isDeleted: 0 }).skip(skip).limit(size)
  let totalElement = await Repository.find({ isDeleted: 0 }).countDocuments()
  ctx.status = 200
  ctx.body = {
    current_page: page,
    per_page: size,
    total: totalElement,
    data: findResult
  }
})

/**
 * @description 新增
 */
router.post('/add', async ctx => {
  const body = ctx.request.body
  const findResult = await Repository.find({ name: body.name })
  if (findResult.length > 0) {
    ctx.status = 400
    ctx.body = { msg: '仓库已存在' }
  } else {
    const newRepository = new Repository({
      name: body.name,
      storage: body.storage
    })
    await newRepository
      .save()
      .then(res => {
        ctx.body = res
      })
  }
})
/**
 * @description 修改仓库信息
 */
router.post('/update', async ctx => {
  let body = ctx.request.body
  const id = ctx.request.body._id
  try {
    const findResult = await Repository.findById(id)
    if (findResult.nowStorage > body.storage) {
      ctx.status = 400
      ctx.response.status = 400
      return
    }
    const updateResult = await Repository.findByIdAndUpdate(id, body)
    if (updateResult) {
      ctx.status = 200
      ctx.body = updateResult
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.response.message = '数据库中无该条数据'
      ctx.body = {
        msg: '修改失败'
      }
    }
  } catch { }
})
/**
 * @description 删除仓库
 */
router.post('/delete', async ctx => {
  const id = ctx.request.body.id
  // 当查找条件(id)存在的时候才执行修改操作
  try {
    const updateResult = await Repository.findByIdAndUpdate(id, { isDeleted: 1 })
    if (updateResult) {
      ctx.status = 200
      ctx.body = updateResult
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.response.message = '数据库中无该条数据'
      ctx.body = {
        msg: '删除失败'
      }
    }
  } catch (err) {

  }
})
/**
 * @description 查看仓库内血袋
 */
router.get('/get', async ctx => {
  const query = ctx.request.query
  const id = query.id
  let page = Number(query.page) ? Number(query.page) : 1
  let size = Number(query.per_page) ? Number(query.per_page) : 9999
  let skip = (page - 1) * size
  // console.log('reposId', id)
  let findResult = await Blood.aggregate([
    {
      $lookup: {
        from: 'volunteers',
        localField: 'volunteerId',
        foreignField: '_id',
        as: 'volunteer'
      }
    },
    {
      $match: {
        reposId: mongoose.Types.ObjectId(id)
      }
    }
  ]).skip(skip).limit(size).collation({ locale: 'en_US' }).sort({ drawDate: -1 })
  let length = findResult.length
  for (let i = 0; i < length; i++) {
    findResult[i].volunteerName = findResult[i].volunteer[0].name
    findResult[i].volunteerId = findResult[i].volunteer[0]._id
    findResult[i].bloodType = findResult[i].volunteer[0].bloodType
    delete findResult[i].volunteer
  }
  let totalElement = await Blood.countDocuments({ isOutdated: 1 })
  ctx.status = 200
  ctx.body = {
    current_page: page,
    per_page: size,
    total: totalElement,
    data: findResult
  }
})
module.exports = router.routes()